package com.gnerv.battle.boot.framework.core.tools.command;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Properties;

/**
 * @author Gnerv LiGen
 */
public abstract class AbstractCommandTools {

    private static final Properties SESSION_PROPERTIES = new Properties();
    private static final int TIME_OUT = 3000;

    static {
        SESSION_PROPERTIES.setProperty("StrictHostKeyChecking", "no");
    }

    public static Session getSession(String username, String password, String host, int port) {
        JSch jsch = new JSch();
        Session session;
        try {
            session = jsch.getSession(username, host, port);
            session.setPassword(password);
            session.setConfig(getSessionProperties());
            session.setTimeout(getTimeOut());
            session.connect();
        } catch (JSchException e) {
            throw new RuntimeException("get session error", e);
        }
        return session;
    }


    public static String readStream(BufferedReader bufferedReader) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line).append("\n");
        }
        String builderString = stringBuilder.toString();
        // 去除颜色字符
        builderString = builderString.replaceAll("\u001B\\[[;\\d]*m", "");
        return builderString;
    }

    public static Properties getSessionProperties() {
        return SESSION_PROPERTIES;
    }

    public static int getTimeOut() {
        return TIME_OUT;
    }
}
